import {
  cadAppLog,
  pickedFaceData,
  pickedLineData,
  pickedVertexData,
} from '@amcax/base';
import { widgetManager } from '@app-cad/module';
import { getNameOfPickedObj } from '@app-cad/common/utils/render';
import { Button, Input } from 'antd';
import './style.scss';
import { markManager } from '@app-cad/common/managers/MarkManager';
import useStateRef from 'react-usestateref';
import { useEffect, useMemo } from 'react';
import { Vector3 } from 'three-legacy';
import { MarkComponentOrigin } from '.';
import cx from 'classnames';

const { TextArea } = Input;

interface IProps {
  pickedObject: pickedVertexData | pickedLineData | pickedFaceData;
  position?: Vector3;
  source?: MarkComponentOrigin;
  onClose?: VoidFunction;
  afterSubmit?: VoidFunction;
}
export default function MarkInput({
  pickedObject,
  position,
  source = MarkComponentOrigin.Panel,
  onClose,
  afterSubmit,
}: IProps) {
  const [text, setText, textRef] = useStateRef<string>('');

  useEffect(() => {
    if (pickedObject == null) {
      setText('');
    }
  }, [pickedObject]);

  const name = useMemo(() => {
    return getNameOfPickedObj(pickedObject);
  }, [pickedObject]);

  const handleClose = () => {
    if (onClose != null) {
      onClose();
      return;
    }
    cadAppLog('[debug]关闭标签面板');
    widgetManager.rightNavigation.hide();
  };

  const handleSubmit = async () => {
    const value = textRef.current;
    if (value === '') {
      alert('标签内容不能为空');
      return;
    }
    await markManager.addMark(pickedObject, textRef.current, position);
    afterSubmit?.();
  };

  return (
    <div
      className={cx(
        'mark-input',
        source === MarkComponentOrigin.Panel &&
          'border-t-2 border-gray-2 border-solid',
      )}
    >
      {source === MarkComponentOrigin.Panel && (
        <div className='mark-model-name'>
          {name || <span className='text-gray-400'>请选择模型...</span>}
        </div>
      )}
      <div className='input-wrapper'>
        <TextArea
          className='select-auto mark-input__text-area'
          rows={2}
          placeholder='请输入标签内容'
          maxLength={80}
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
      </div>
      <div className='actions-wrapper'>
        <Button onClick={handleClose}>取消</Button>
        <Button
          type='primary'
          disabled={text === '' || pickedObject == null}
          onClick={handleSubmit}
        >
          发送
        </Button>
      </div>
    </div>
  );
}
